import request from 'request-promise'
const base = 'https://api.weixin.qq.com/cgi-bin/'

const api = {
  accessToken: `${base}token?grant_type=client_credential`
}
export default class Wechat {
  constructor (options) {
    this.opts = Object.assign({}, options)

    this.appID = options.appID,
    this.appSecret = options.appSecret
    this.getAccessToken = options.getAccessToken
    this.saveAccessToken = options.saveAccessToken

    this.fetchAccessToken()
  }

  async request (options) {
    options = Object.assign({}, options, { json: true })
    try {
      const response = await request(options)
      return response
    } catch (e) {
      console.log(e)
    }
  }

  async fetchAccessToken () {
    let data = await this.getAccessToken()

    if (this.isValidAccessToken(data)) {
      data = await this.updateAccessToken()
    }
    console.log(data)
    if (data) {
      await this.saveAccessToken(data)
    }
    return data
  }

  async updateAccessToken () {
    const url = `${api.accessToken}&appid=${this.appID}&secret=${this.appSecret}`
    const data = this.request({url: url})
    const now = (new Date().getTime())
    const expires_in = now + (data.expires_in - 20) * 1000
    data.expires_in = expires_in
    return data
  }

  isValidAccessToken (data) {
    if (!data || !data.access_token || !data.expires_in) {
      return false
    }

    const expires_in = data.expires_in
    const now = (new Date().getTime())

    if (now < expires_in) {
      return true
    } else {
      return false
    }
  }

}
